package com.ruitaowang.admin.view.api;

import com.ruitaowang.account.security.LYSecurityUtil;
import com.ruitaowang.core.domain.*;
import com.ruitaowang.core.web.BaseController;
import com.ruitaowang.core.web.MsgOut;
import com.ruitaowang.goods.service.*;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import tech.lingyi.wx.msg.out.TemplateData;
import tech.lingyi.wx.msg.out.TemplateItem;
import wx.wechat.service.mp.MPService;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
public class APICommentController extends BaseController {

    @Autowired
    private CommentService commentService;
    @Autowired
    private OrderProdService orderProdService;
    @Autowired
    private WXUserinfoService wxUserinfoService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private ShoppingOrderService shoppingOrderService;
    @Autowired
    private CompanyService companyService;
    @Value("${host.api}")
    private String host;

    /**
     * @api {get} /api/wap/comment 评论-查询所有
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/wap/comment
     *
     * @apiName list
     * @apiGroup comment
     *
     * @apiParam {String} remark 备注.
     * @apiParam {long} goodsId 商品ID.
     * @apiParam {long} companyId 商户ID.
     * @apiParam {String} imgContent 图片JSON.
     * @apiParam {byte} commentType 评论类型.
     * @apiParam {String} commentContent 评论内容.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *                   "ctime":1502870415259,
     *                   "id":8,
     *                   "imgContent":"",
     *                   "commentType":0,
     *                   "commentContent":"",
     *                   "companyId":0,
     *                   "goodsId":0,
     *                   "mtime":1502870415259,
     *                   "remark":"",
     *                   "userId":6
     *                   "rstatus":0,
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/wap/comment"
     *  }
     */
    @RequestMapping("/api/wap/comment")
    public String list(Comment comment) {
        MsgOut o = MsgOut.success(commentService.select(comment));
        return this.renderJson(o);
    }

    /**
     * @api {get} /api/wap/comment 评论-(分页)查询所有
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/wap/comment
     *
     * @apiName listForPage
     * @apiGroup comment
     *
     * @apiParam {int} page 第几页.
     * @apiParam {int} rows 每页条数.
     * @apiParam {String} remark 备注.
     * @apiParam {long} goodsId 商品ID.
     * @apiParam {long} companyId 商户ID.
     * @apiParam {String} imgContent 图片JSON.
     * @apiParam {byte} commentType 评论类型.
     * @apiParam {String} commentContent 评论内容.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *                   "ctime":1502870415259,
     *                   "id":8,
     *                   "imgContent":"",
     *                   "commentType":0,
     *                   "commentContent":"",
     *                   "companyId":0,
     *                   "goodsId":0,
     *                   "mtime":1502870415259,
     *                   "remark":"",
     *                   "userId":6
     *                   "rstatus":0,
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/wap/comment"
     *  }
     */
    @RequestMapping("/api/wap/comment/page")
    public String listForPage(Comment comment, int page) {
        comment.setPage(page);
        if (!ObjectUtils.isEmpty(comment.getSidx())) {
            comment.setOrderBy(comment.getSidx() + " " + comment.getSord() + "," + comment.getOrderBy());
        }
        MsgOut o = MsgOut.success(commentService.selectForPage(comment));
        o.setRecords(comment.getRecords());
        o.setTotal(comment.getTotal());
        return this.renderJson(o);
    }
    /**
     * @api {get} /api/wap/comment 评论-(分页)查询所有
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/wap/comment
     *
     * @apiName listForPage
     * @apiGroup comment
     *
     * @apiParam {int} page 第几页.
     * @apiParam {int} rows 每页条数.
     * @apiParam {String} remark 备注.
     * @apiParam {long} goodsId 商品ID.
     * @apiParam {long} companyId 商户ID.
     * @apiParam {String} imgContent 图片JSON.
     * @apiParam {byte} commentType 评论类型.
     * @apiParam {String} commentContent 评论内容.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *                   "ctime":1502870415259,
     *                   "id":8,
     *                   "imgContent":"",
     *                   "commentType":0,
     *                   "commentContent":"",
     *                   "companyId":0,
     *                   "goodsId":0,
     *                   "mtime":1502870415259,
     *                   "remark":"",
     *                   "userId":6
     *                   "rstatus":0,
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/wap/comment"
     *  }
     */
    @RequestMapping("/api/admin/comment/page")
    public String selectForPage(Comment comment, int page) {
        comment.setPage(page);
        if (!ObjectUtils.isEmpty(comment.getSidx())) {
            comment.setOrderBy(comment.getSidx() + " " + comment.getSord() + "," + comment.getOrderBy());
        }
        MsgOut o = MsgOut.success(commentService.selectAdForPage(comment));
        o.setRecords(comment.getRecords());
        o.setTotal(comment.getTotal());
        return this.renderJson(o);
    }
    /**
     * @api {post} /api/wap/comment 评论-创建
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/wap/comment
     *
     * @apiName create
     * @apiGroup comment
     *
     * @apiParam {String} remark 备注.
     * @apiParam {long} goodsId 商品ID.
     * @apiParam {long} companyId 商户ID.
     * @apiParam {String} imgContent 图片JSON.
     * @apiParam {byte} commentType 评论类型.
     * @apiParam {String} commentContent 评论内容.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *                   "ctime":1502870415259,
     *                   "id":8,
     *                   "imgContent":"",
     *                   "commentType":0,
     *                   "commentContent":"",
     *                   "companyId":0,
     *                   "goodsId":0,
     *                   "mtime":1502870415259,
     *                   "remark":"",
     *                   "userId":6
     *                   "rstatus":0,
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/wap/comment"
     *  }
     */
    @RequestMapping(value = "/api/wap/comment", method = RequestMethod.POST)
    public String create(Comment comment) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        comment.setUserId(user.getId());
        commentService.insert(comment);
        MsgOut o = MsgOut.success(comment);
        return this.renderJson(o);
    }
    /**
     * @api {put} /api/wap/comment 评论-修改
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/wap/comment
     *
     * @apiName update
     * @apiGroup comment
     *
     * @apiParam {String} remark 备注.
     * @apiParam {long} goodsId 商品ID.
     * @apiParam {long} companyId 商户ID.
     * @apiParam {String} imgContent 图片JSON.
     * @apiParam {byte} commentType 评论类型.
     * @apiParam {String} commentContent 评论内容.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *                   "ctime":1502870415259,
     *                   "id":8,
     *                   "imgContent":"",
     *                   "commentType":0,
     *                   "commentContent":"",
     *                   "companyId":0,
     *                   "goodsId":0,
     *                   "mtime":1502870415259,
     *                   "remark":"",
     *                   "userId":6
     *                   "rstatus":0,
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/wap/comment"
     *  }
     */
    @RequestMapping(value = "/api/wap/comment", method = RequestMethod.PUT)
    public String update(Comment comment) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        commentService.update(comment);
        MsgOut o = MsgOut.success(comment);
        return this.renderJson(o);
    }
    /**
     * @api {delete} /api/wap/comment/{id} 评论-删除
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/wap/comment/{id}
     *
     * @apiName delete
     * @apiGroup comment
     *
     * @apiParam {long} id 评论ID.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":1
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/wap/comment/{id}"
     *  }
     */
    @RequestMapping(value = "/api/wap/comment/{id}", method = RequestMethod.DELETE)
    public String delete(@PathVariable("id") Long id) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        MsgOut o = MsgOut.success(commentService.delete(id));
        return this.renderJson(o);
    }
    /**
     * @api {get} /api/wap/comment/{id} 评论-单个查询
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/wap/comment/{id}
     *
     * @apiName findCommentId
     * @apiGroup comment
     *
     * @apiParam {long} id 评论ID.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *                   "ctime":1502870415259,
     *                   "id":8,
     *                   "imgContent":"",
     *                   "commentType":0,
     *                   "commentContent":"",
     *                   "companyId":0,
     *                   "goodsId":0,
     *                   "mtime":1502870415259,
     *                   "remark":"",
     *                   "userId":6
     *                   "rstatus":0,
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/wap/comment/{id}"
     *  }
     */
    @RequestMapping(value = "/api/wap/comment/{id}", method = RequestMethod.GET)
    public String findCommentId(@PathVariable("id")Long  id) {
        MsgOut o = MsgOut.success(commentService.selectByPK(id));
        return this.renderJson(o);
    }

    /**
     *  对商品进行评论
     * @param comment
     * @param userId
     * @return
     */
    @RequestMapping(value = "/api/wap/comment/creat", method = RequestMethod.POST)
    public String createComment(Comment comment,OrderProd orderProd,@RequestHeader(value="headId",required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        if (ObjectUtils.isEmpty(comment.getCommentType())) {
            if (ObjectUtils.isEmpty(comment.getImgContent())) {
                comment.setCommentType((byte)1);
            } else {
                comment.setCommentType((byte)2);
            }
        }
        comment.setUserId(Long.parseLong(userId));
        commentService.insert(comment);
        orderProd.setEvaluate((byte)1);
        orderProdService.update(orderProd);
        orderProd = orderProdService.selectByPK(orderProd.getProdId());
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String date =  df.format(new Date());
        Order order = orderService.selectByPK(shoppingOrderService.selectByPK(orderProd.getOrderId()).getOrderId());
        buildQRNotify(companyService.selectByPK(comment.getCompanyId()).getUserId(),order.getOrderSn(),date);
        MsgOut o = MsgOut.success(comment);
        return this.renderJson(o);
    }

    /**
     * 用户提交评价推送消息
     * @param userId
     * @param orderSn
     * @param date
     */
    public void buildQRNotify(Long userId,String orderSn,String date) {
        TemplateData templateData = TemplateData.New();
        SNSWXUserinfo snswxUserinfo = wxUserinfoService.selectByPK(userId);
        if (ObjectUtils.isEmpty(snswxUserinfo)) {
            return;
        }
        templateData.setTouser(snswxUserinfo.getOpenid());
        templateData.setTemplate_id("yVGalziwLZZkIbP9ThVMv7jI9J7IeKjz3FjJimGavjw");
        templateData.setTopcolor("FF0000");
        templateData.setData(new TemplateItem());
        templateData.add("first", "恭喜您，已有用户提交了评价，请您前去查看评价详情", "#173177");
        templateData.setUrl(host + "/wap/wx/login?fk=1-35-0-0");//店家故事页面/wap/dcv2/check_number.html
        templateData.add("keyword1", orderSn, "#0044BB");
        templateData.add("keyword2", date, "#0044BB");
        templateData.add("remark", "您可进入到个人中心，通过评价管理查看评价", "#FF3333");
        try {
            LOGGER.info("templateData {}", templateData);
            new MPService().sendAPIEnter4TemplateMsg(templateData);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
